const express = require("express");
const cors = require("cors");
const app = express();
const { secretKey } = require("./config");
const expressJWT = require("express-jwt");
const multer = require("multer")
//跨域
app.use(cors());

//post请求
app.use(express.json());
app.use(express.urlencoded());

//挂载登录注册路由
const userRouter = require("./router/user");
app.use("/user", userRouter);

// 访问静态文件  上传的图片的路径
const path = require("path")
app.use('/uploads', express.static('uploads'));


app.use(
  expressJWT({ secret: secretKey, algorithms: ["HS256"] }).unless({
    path: ["/register", "/login", /^\/uploads\//],
  })
);

//挂载角色管理路由
const roleRouter = require("./router/roles");
app.use("/api", roleRouter);

//挂载权限路由
const rightRouter = require("./router/rights");
app.use("/api", rightRouter);

//挂载商品分类路由
const categoriesRouter = require("./router/categories");
app.use("/api", categoriesRouter);

//挂载分类参数管理路由
const attributesRouter = require("./router/attributes");
app.use("/api", attributesRouter);

//挂载商品管理路由
const goodsRouter = require("./router/goods");
app.use("/api", goodsRouter);

//上传文件
const fileRouter = require("./router/file");
app.use("/api", fileRouter);

const Joi = require("joi");
//错误中间件
app.use(function (err, req, res, next) {
  // 4.1 Joi 参数校验失败
  if (err instanceof Joi.ValidationError) {
    return res.send({
      status: 1,
      message: err.message,
    });
  }

  if (err instanceof multer.MulterError) {
    return res.send({
      status: 1,
      message: '文件上传报错',
      type: err.message
    });
  } 
  // 4.2 未知错误
  res.send({
    status: 101,
    message: err.message,
  });
});

app.listen(3000, () => {
  console.log("3000 running");
});
